import axios from 'axios';
import config from '@/utils/config';
const { apiHost } = config;
// 文件导出
export const ajaxDownload =
  (url, type = 'post') =>
  (params, { downloadSuffix = '.xlsx' } = {}) => {
    const formJson = Object.prototype.toString.call(params) === '[object Array]' ? params : Object.assign({}, params);
    return axios({
      method: type,
      url: `${apiHost}${url}`,
      data: JSON.stringify(formJson),
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json',
        Authorization: localStorage.Authorization,
      },
    })
      .then((res) => {
        if (res.headers['content-disposition']) {
          const url = window.URL.createObjectURL(new Blob([res.data]));
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = url;
          const fileName = res.headers['content-disposition'].split('filename=')[1];
          link.download = decodeURIComponent(fileName);
          document.body.appendChild(link);
          link.click();
          return res;
        }
      })
      .catch((error) => {
        console.log('response: ', error);
        return Promise.reject(error);  
      });
  };
